package ua.yandex.skipass;

import java.util.Calendar;
import java.util.Date;

/**
 *
 * @author Кирилл
 */
public class SkiPassWorkdayRacesLimitedCard extends SkiPassCard {

    private static final int WORKDAY_IN_WEEK = 5;
    private int numberOfRemainingRaces;
    
    SkiPassWorkdayRacesLimitedCard(Date activationDate, Date expirationDate,  
                                   int id, SkiPassRaces race) {
        super(activationDate, expirationDate, id,
                SkiPassType.WORKDAY_RACES_LIMITED);
        if (expirationDate.getTime() < activationDate.getTime()) {
            throw new OutOfBoundException(
                    "This card will be activated after it has expired");
        }
        if (expirationDate.getTime() > 
                getTheEndOfCurrentWeek(activationDate).getTime()) {
            throw new OutOfBoundException(
                    "Duration of required season ticket exceed max possible");
        }
        numberOfRemainingRaces = race.getNumberOfRaces();
    }
    
    SkiPassWorkdayRacesLimitedCard(Date activationDate, 
                                   int id, SkiPassRaces race) {
        super(activationDate, getTheEndOfCurrentWeek(activationDate),
                id, SkiPassType.WORKDAY_RACES_LIMITED);
        numberOfRemainingRaces = race.getNumberOfRaces();
    }

    SkiPassWorkdayRacesLimitedCard(int id, SkiPassRaces race) {
        super(new Date(System.currentTimeMillis()), getTheEndOfCurrentWeek(),
                id, SkiPassType.WORKDAY_RACES_LIMITED);
        numberOfRemainingRaces = race.getNumberOfRaces();
    }
    
    
    private static Date getTheEndOfCurrentWeek(Date activationDate) {
        Date currentDate = activationDate;
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentDate);
        calendar.add(Calendar.WEEK_OF_MONTH, WORKDAY_IN_WEEK);
        Date expirationDate = calendar.getTime();
        return expirationDate;
    }
    private static Date getTheEndOfCurrentWeek() {
        return getTheEndOfCurrentWeek(new Date(System.currentTimeMillis()));
    }
    
    @Override
    public boolean passIsAllowed() {
        if (isBlocked()) {
            return false;
        }
        if (isExpired()) {
            return false;
        }
        if (SkiPassSystem.isWeekend()) {
            return false;
        }
        return numberOfRemainingRaces > 0;
    }
    
    public void decreaseNumberOfRaces() {
        if (numberOfRemainingRaces <= 0) {
            throw new OutOfBoundException("You have no available races");
        }
        numberOfRemainingRaces--;
    }
    
    public int getNumberOfRemainingRaces() {
        return numberOfRemainingRaces;
    }
    
}
